package org.bdware.irp.irplib.crypto;

import io.netty.channel.ChannelHandlerContext;
import org.bdware.irp.irplib.exception.EnvelopeResendException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeSet;

public class NoResendPacketReceiveBuffer extends AbstractPacketReceiveBuffer {

    HashMap<Integer,IrpMessagePacket> packetMap;
    int messageLength;
    int currentLength;
    TreeSet<Integer> sortedPacketNumberSet;

    public NoResendPacketReceiveBuffer(int requestId, ChannelHandlerContext ctx) {
        super(requestId);
        sortedPacketNumberSet = new TreeSet<>();
        packetMap = new HashMap<>();
        messageLength = 0;
        currentLength = 0;
    }

    @Override
    public boolean isCompleted() {
        return messageLength <= currentLength;
    }

    @Override
    public void addMessagePacket(IrpMessagePacket messagePacket) throws EnvelopeResendException {
        if(messageLength == 0 ) messageLength = messagePacket.irpMessageEnvelope.messageLength;
        currentLength += messagePacket.bodyPacket.length;
        packetMap.put(messagePacket.irpMessageEnvelope.sequenceNumber,messagePacket);
        sortedPacketNumberSet.add(messagePacket.irpMessageEnvelope.sequenceNumber);
    }

    @Override
    public ArrayList<IrpMessagePacket> getSortedIrpMessagePackets() {
        //升序排列messagePacket
        ArrayList<IrpMessagePacket> packets = new ArrayList<>();
        for(int key:sortedPacketNumberSet){
            packets.add(packetMap.get(key));
        }
        return packets;
    }
}
